package net.maku.events.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
import lombok.AllArgsConstructor;
import net.maku.framework.common.utils.PageResult;
import net.maku.framework.mybatis.service.impl.BaseServiceImpl;
import net.maku.events.convert.UserJoinActivityConvert;
import net.maku.events.entity.UserJoinActivityEntity;
import net.maku.events.query.UserJoinActivityQuery;
import net.maku.events.vo.UserJoinActivityVO;
import net.maku.events.dao.UserJoinActivityDao;
import net.maku.events.service.UserJoinActivityService;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户参与的活动
 *
 * @author 阿沐 babamu@126.com
 * @since 1.0.0 2025-03-22
 */
@Service
@AllArgsConstructor
public class UserJoinActivityServiceImpl extends BaseServiceImpl<UserJoinActivityDao, UserJoinActivityEntity> implements UserJoinActivityService {

    @Override
    public PageResult<UserJoinActivityVO> page(UserJoinActivityQuery query) {
        IPage<UserJoinActivityEntity> page = baseMapper.selectPage(getPage(query), getWrapper(query));

        return new PageResult<>(UserJoinActivityConvert.INSTANCE.convertList(page.getRecords()), page.getTotal());
    }

    private LambdaQueryWrapper<UserJoinActivityEntity> getWrapper(UserJoinActivityQuery query) {
        LambdaQueryWrapper<UserJoinActivityEntity> wrapper = Wrappers.lambdaQuery();
        return wrapper;
    }

    @Override
    public void save(UserJoinActivityVO vo) {
        UserJoinActivityEntity entity = UserJoinActivityConvert.INSTANCE.convert(vo);

        baseMapper.insert(entity);
    }

    @Override
    public void update(UserJoinActivityVO vo) {
        UserJoinActivityEntity entity = UserJoinActivityConvert.INSTANCE.convert(vo);

        updateById(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(List<Long> idList) {
        removeByIds(idList);
    }

    @Override
    public Map<Long, Long> getUserJoinActivity(List<Long> activityIdList, Integer businessType) {
        List<UserJoinActivityEntity> entityList = this.list(new LambdaQueryWrapper<UserJoinActivityEntity>()
                .in(UserJoinActivityEntity::getActivityId, activityIdList)
                .eq(UserJoinActivityEntity::getBusinessType, businessType));
        if (CollectionUtils.isNotEmpty(entityList)) {
            return entityList.stream().collect(Collectors.groupingBy(UserJoinActivityEntity::getActivityId, Collectors.counting()));
        }
        return Map.of();
    }

}